//安装 express 包  『npm i express』
//引入 express 框架
const express = require('express');

//创建服务对象
const app = express();

//1. 中间件函数
let recordMiddleware = function(request, response, next){
    //记录时间
    console.log(Date.now());
    //执行 next 函数
    next();
}

let testMiddleware = function(request, response, next){
    console.log('Test test');
    next();
}

let checkVipMiddleware = function(request, response, next){
    if(request.query.vip === '1'){
        next();
    }else{
        response.send('<h1>访问受限, 请联系管理员</h1>')
    }
}

//2. 设置中间件 『全局中间件』
app.use(recordMiddleware, testMiddleware);
// app.use(testMiddleware);

//创建路由规则
app.get('/', (request, response) => {
    response.end('home home home');
});

// 必须传递 url 参数 vip=1 方可执行, 如果没有传递该参数, 则响应无权限
app.get('/admin', [checkVipMiddleware], (request, response) => {
    response.send('欢迎回来后台!!');
});

app.get('/cart', checkVipMiddleware, (request, response) => {
    response.send('购物车页面');
});

app.get('/setting', checkVipMiddleware, (request, response) => {
    response.send('设置页面');
});

//监听端口 启动服务
app.listen(80, () => {
    console.log('服务已经启动 80 端口监听中');
});

